<?php

if(!defined('_LIB_SEARCH_')) {
define('_LIB_SEARCH_', 1);

include  _FLEP_LIB_DIR_.'db.inc.php';

function flep_search(&$data, $query, $idx = 'data') {
  $found = false;
  $db = flep_db_connect();
  if (!flep_db_error($db)) {
    if (flep_db_query($db, $query)) {
      for ($i = 0; flep_db_fetch_assoc($db); $i++) {
        $data[$idx][$i] = flep_db_row($db);
        $found = true;
      }
      flep_db_free($db);
    } else {
      $data['msg'] = flep_db_error($db);
      $data['db_errno'] = $db['errno'];;
    }
    flep_db_close($db);
  } else {
    $data['db_errno'] = $db['errno'];
    $data['msg'] = $db['error'];
    $found = false;
  }
  return $found;
}

function flep_search_all(&$data, $idx = 'data') {
  $alias = "*, ".$data['table'].".id";
  $joins = "";
  $where = "";
  $order = "";
  $limit = "";

  if (array_key_exists('alias', $data)) {
    $alias = implode(', ', $data['alias']);
  }
  if (array_key_exists('joins', $data) && array_key_exists('join_fields', $data)) {
    $joins = sprintf('LEFT JOIN (%s) ON (%s)', implode(', ', $data['joins']), implode(' AND ', $data['join_fields']));
  }
  if (array_key_exists('search', $data) && $data['search'] !== '') {
    $where = 'WHERE (`' . implode('` LIKE \'%'.$data['search'].'%\' OR `', $data['search_fields']) . '` LIKE \'%'.$data['search'].'%\' )';
  }
  if (array_key_exists('where', $data) && !empty($data['where'])) {
    $where = ($where == ""? 'WHERE ' : $where . ' AND ') . implode(' AND ', $data['where']);
  }
  if (!(array_key_exists('sort', $data))) {
    $data['sort'] = 'ASC';
  }
  if (array_key_exists('order', $data)) {
    $order = sprintf('ORDER BY %s %s', $data['order'], $data['sort']);
  }
  if (!(array_key_exists('offset', $data))) {
    $data['offset'] = 0;
  }
  if (!(array_key_exists('rows', $data))) {
    $data['rows'] = _FLEP_MAX_ROWS_;
  }
  if (!array_key_exists('limit', $data)) {
    $limit = sprintf('LIMIT %s, %s', $data['offset'], $data['rows']);
  }
  $query = sprintf('SELECT %2$s FROM %1$s %3$s %4$s %5$s %6$s', $data['table'], $alias , $joins, $where, $order, $limit);
  return flep_search($data, $query, $idx);
}

function flep_search_count(&$data){
  $tmp_alias = (isset($data['alias'])? $data['alias']: null);
  $tmp_limit = (isset($data['limit'])? $data['limit']: null);
  $data['alias'] = array("COUNT(*) AS 'total'");
  $data['limit'] = '';
  $result = flep_search_all($data, 'total');
  if ($tmp_alias !== null ) $data['alias'] = $tmp_alias; else unset($data['alias']);
  if ($tmp_limit !== null ) $data['limit'] = $tmp_alias; else unset($data['limit']);
  return $result;
}

}
?>
